(function(window, undefined) {
	var Account = {};
	var userJoinInfo={
		_phone:0,
		_name:'',
		_password:0,
		_gender:'male',
		_birth:'',
		_description:''
		
	};
	window.Account = window.Account || Account;
	
	Account.isLogin = function(){
		var _isLogin = false;
					
		if(sessionStorage.getItem('user_id')) {
			_isLogin = true;
			
		}
		
		return _isLogin;
	};
	
	var loadOwnStoreId = function(user_id){
		alert(user_id);
		$.ajax({
			type:'post',
			url:ajaxURL+'account.php?action=loadOwnStoreId',
			data:{user_id:user_id},
			async:false,
			dataType:'json',
			success:function(result){
				alert('ss');
				console.log('isOwnerUser');
				console.log(result.store_id);
				sessionStorage.setItem('owner_store_id',result.store_id);
			}
		});
	};
	/* 헤더의 로그아웃부분 topheader.php*/
	Account.headerAccountBlock = function(){
		if(sessionStorage.getItem('owner_store_id')){
			$('#topLog').html('<a class="logInfo" href="seller_store.php">미즈컨테이너(홍대점)</a> <a href="index.php" class="logoutBtn">로그아웃</a>'
			+' <a href="seller_store.php?id=8751">마이 스토어</a>'
			+'| <a href="seller_report.php">방문고객 리포트</a>'
			+'| <a href="seller_friend.php">고객관리</a>'
			+' | <a href="#" class="headLogMoreBtn">더보기</a>'
			+ '<div class="headLogMore">'
			+'<a href="seller_coupon.php">쿠폰관리</a><br/>'
			+'<a href="seller_point.php">포인트관리</a><br/>'
			+'<a href="seller_service.php">서비스 이용내역</a><br/>'
			+'<a href="seller_setting.php">설정</a><br/>'
			+'</div>');
	
		}
		if(sessionStorage.getItem('user_id')){
			$('#topLog a:nth(0)').html(sessionStorage.getItem('user_name'));
			$('.logoutBtn').off('click').on('click', function(event) {
				event.preventDefault();
				Account.logout();
					
			});
		}else{
			$('#topLog').removeClass('logon');
			$('#topLog').html('<a href="login.php" class="loginBtn">로그인</a> <a href="join.php">회원가입</a>');
		}
		
		
	};
	
	/*우측중간에 로그인 블록 index.php,login.php*/
	Account.LoginBlock = function(){
		var selector = '#loginWrap';
		$(selector).empty();
		$(selector).removeClass('logon');
		template.LoginBlock(selector);
		
		$('#mainLoginBtn').off('click').on('click', function(event) {
			event.preventDefault();
			Account.loginByPhone();
			
		});
	};
	
	/*우측중간에 로그인 블록 index.php*/
	Account.LoginedBlock = function(){
		var selector = '#loginWrap';
		userInfo(function(result){

			$(selector).empty();
			$(selector).addClass('logon');
			$.each(result,function(){
				if(this.point == null){
					this.point = 0;
				}else if(this.total_point == null){
					this.total_point = 0;
				}
				if(this.image==null){
					this.image='images/default_user.png';
				}
									
				template.LoginedBlock(this,selector);
			});
		});
	};
	
	/*회원가입 - 약관동의 join.php*/
	Account.joinBlock1= function(){	
		
		
		$('#joinBtn1').off('click').on('click', function(event) {
			event.preventDefault();
			if($('input[type="checkbox"]:nth(0)').is(':checked') && $('input[type="checkbox"]:nth(1)').is(':checked')) {
				$('section').hide();$('section:nth(1)').fadeIn();
				joinBlock2();
			}else if(!$('input[type="checkbox"]:nth(0)').is(':checked') && $('input[type="checkbox"]:nth(1)').is(':checked')) {
				alert(NEED_SEVICE_AGREE_MESSAGE);
			}else if($('input[type="checkbox"]:nth(0)').is(':checked') && !$('input[type="checkbox"]:nth(1)').is(':checked')) {
				alert(NEED_PRIVACY_AGREE_MESSAGE);
			}else if(!$('input[type="checkbox"]:nth(0)').is(':checked') && !$('input[type="checkbox"]:nth(1)').is(':checked')) {
				alert(NEED_AGREE_MESSAGE);
			}

		});
	};
	
	/*회원가입 - 휴대폰 인증 join2.php*/
	var joinBlock2= function(){	
		joinBlock2.check_phone = 0;
		
		$('#sendNumber').off('click').on('click', function(event) {
			event.preventDefault();
			if($('#phoneNumber2').val()==''&&$('#phoneNumber3').val()==''){
				$('#phoneNumber2').focus();
			}else if($('#phoneNumber2').val()!=''&&$('#phoneNumber3').val()==''){
				$('#phoneNumber3').focus();
			}else{
				checkPhone();
			}
			
		});
		$("#authBtn").off('click').on('click', function(event) {
			event.preventDefault();
			if($('#authPhone').val()==''){
				$('#authPhone').focus();
			}
		});
		
		$('#joinBtn2').off('click').on('click', function(event) {
			event.preventDefault();
			if(joinBlock2.check_phone==1) {
				$('section').hide();$('section:nth(2)').fadeIn();
				joinBlock3();
			}else{
				alert(NEED_AUTHPHONE);
				$('#phoneNumber2').focus();
			}

		});
	};
	
	/*회원가입 - 정보 입력 join3.php*/
	var joinBlock3= function(){	
		$('#joinPhone').val(userJoinInfo._phone);
		
		$('#joinBtn3').off('click').on('click', function(event) {
			checkInput();
		});
		$('#joinRePW').change(function() {
			checkPassword();
		});
	};
	
	/*비밀번호 찾기 findPw.php*/
	Account.findPwBlock= function(){	
		_type='password';
		$('#authBtn').off('click').on('click', function(event) {
			event.preventDefault();
			 
			sendmessage(_type);
			alert(SUCCESS_SEND_PASSWORD);
			
		});
		
	};
	
	
	/*설정 블록 mysetting.php*/
	Account.mySettingBlock = function(){
		var selector = '.left table';
		userInfo(function(result){

			
			$(selector).addClass('logon');
			$.each(result,function(){
				if(this.gender=='female'){
					this.gender='여자';
				}else if(this.gender=='female'){
					this.gender='남자';
				}
				$('.left table:nth(0) tr:nth(0) td').html(this.phone);
				$('.left table:nth(0) tr:nth(2) td').html(this.gender);
				$('.left table:nth(0) tr:nth(3) td').html(this.birthday);
				$('.left table:nth(0) tr:nth(4) td').html(this.name);
				$('.left table:nth(0) tr:nth(5) td > img').attr("src",this.image);
				$('.left table:nth(0) tr:nth(5) td > img').css({"width":"100px","height":"100px"});
				$('.left table:nth(0) tr:nth(6) td input').val(this.description);
			});
		});
		$('#changPwdBtn').off('click').on('click', function(event) {
			event.preventDefault();
			 $('#editPw,.modalBg').show();
			
		});
		$('.modalClose,#cancelBtn').off('click').on('click', function(event) {
			event.preventDefault();
			 $('#editPw,.modalBg').hide();
			 $('#pwdTable input').val('');
			
		});
		
		$('#pwdConfirmBtn').off('click').on('click', function(event) {
			event.preventDefault();
			 changePassword();	
		});
		$('#modifyBtn').off('click').on('click', function(event) {
			event.preventDefault();
			 modifyInfo();	
		});
		
		changeProfileImage();
		
	};
	
	var changeProfileImage = function(){
		var _btnUpload=$('#upload');
		var _time = new Date();
		var _user_id = sessionStorage.getItem('user_id');
		var _fileName = _user_id+"_"+_time.getYear() + "_" + _time.getMonth() + "_" + _time.getDay() + "_" + _time.getDate() + "_" + _time.getHours() + "_" + _time.getMinutes() + "_" + _time.getSeconds();
		var _degree=0;		
		
		new AjaxUpload(_btnUpload, {
			action: ajaxURL+'image.php?action=imgUpload&degree='+_degree,
			name: 'uploadfile',
			data: {user_id:_user_id,type:'profile',fileName:_fileName},
			onSubmit: function(file, ext){
				
				
				if (! (ext && /^(jpg|png|jpeg|gif)$/.test(ext))){ 
                    // extension is not allowed 
					alert('Only JPG, PNG or GIF files are allowed');
					return false;
				}

			},
			onComplete: function(file, response){
				Account.mySettingBlock();
				
				
			}
		});
	}
	
	Account.loginByPhone = function() {
		var _phone = $('#logID').val() || $('#loginPageID').val();
		var _password = $('#logPW').val() || $('#loginPagePW').val();
		$.ajax({
			type : "post",
			url : ajaxURL + "account.php?action=isloginPhone",
			dataType : "json",
			data : {
				phone : _phone,
				password : _password
			},
			success : function(result) {
				if(result == "no") {
					alert(FAIL_LOGIN_MESSAGE0);
				} else if(result == false) {
					alert(FAIL_LOGIN_MESSAGE1);
				} else {
					if ($('#autoCheckbox').is(':checked')) {
						setAutoLogin(result);
					}else{
						/*상인이 로그인 할 경우*/
						if(result[0].owner_store_id){
							sessionStorage.setItem('owner_store_id', result[0].owner_store_id);
						}
					
						sessionStorage.setItem('user_id', result[0].user_id);
						sessionStorage.setItem('user_name', result[0].name);
						sessionStorage.setItem('user_image' , result[0].image);
						//loadOwnStoreId(result[0].user_id);
					}
					//alert(SUCCESS_LOGIN_MESSAGE);
					location.href='index.php';
				}
			}
		});
	};
	
	var userInfo = function(_callback) {
		var _user_id = sessionStorage.getItem('user_id');
		
		$.ajax({
			type : "post",
			url : ajaxURL + "account.php?action=userInfo",
			dataType : "json",
			data : {
				user_id : _user_id
			},
			success : function(result) {
				_callback(result);
				
				
				
			}
		});
	};
	
	var setAutoLogin = function(__loginInformation){
		if(!__loginInformation){
			alert(NONE_PARAMETER);
			return;
		}
		
		localStorage.setItem('auto_user_id',__loginInformation[0].user_id);
		localStorage.setItem('auto_user_name',__loginInformation[0].name);
		localStorage.setItem('auto_user_image',__loginInformation[0].image);
		Account.autoLogin();

	};
	
	/*자동 로그인 체크되있는지 확인하고 실행*/
	Account.autoLogin = function(){
		
		var _autoUserId = localStorage.getItem('auto_user_id');
		var _autoUserName = localStorage.getItem('auto_user_name');
		var _autoUserImage = localStorage.getItem('auto_user_image');
		
		var _userId = sessionStorage.getItem('user_id');
		var _userName = sessionStorage.getItem('user_name');
		var _userImage = sessionStorage.getItem('user_image');
	
		if(_autoUserId){
			sessionStorage.setItem('user_id', _autoUserId);
			sessionStorage.setItem('user_name', _autoUserName);
			sessionStorage.setItem('user_image', _autoUserImage);
			location.href='index.php';
		
		}else if(_userId){
			sessionStorage.setItem('user_id', _userId);
			sessionStorage.setItem('user_name', _userName);
			sessionStorage.setItem('user_image', _userImage);
			location.href='index.php';
		}
		
	};
	
	 
	/*로그아웃*/
	Account.logout = function() {
		sessionStorage.removeItem('user_id');
		sessionStorage.removeItem('user_name');
		sessionStorage.removeItem('user_image');
		sessionStorage.removeItem('fb_token');
		sessionStorage.removeItem('tw_token');
		sessionStorage.removeItem('tw_token_secret');
		sessionStorage.removeItem('owner_store_id');
		
		localStorage.removeItem('auto_user_id');
		localStorage.removeItem('auto_user_name');
		localStorage.removeItem('auto_user_image');
		location.href='index.php';
	};
	
	/*전화번호 중복확인*/
	var checkPhone = function(){
		var _type='auth';
		userJoinInfo._phone = $("#phoneNumber1").val()+$("#phoneNumber2").val()+$("#phoneNumber3").val();

		$.ajax({
			type : "post",
			url : ajaxURL + "account.php?action=checkPhone",
			dataType : "json",
			data : {
				phone : userJoinInfo._phone
			},
			success : function(result) {
				if(result==true){
					sendmessage(_type);
					alert(SUCCESS_SEND_AUTHPHONE);
				}else if(result==false){
					alert(UNUSABLE_PHONE);
					$("#phoneNumber3").val('');
					$("#phoneNumber2").val('').focus();
				}
				
					
			}
		});	
	};
	
	/*인증번호 문자메시지 전송*/
	var sendmessage = function(_type){
		var _random_code;
		var _phone = $("#phoneNumber1").val()+$("#phoneNumber2").val()+$("#phoneNumber3").val();

		var _data = new Array('1', '2', '3', '4', '5', '6', '7', '8', '0', '1', '2', '3', '4', '5', '6', '7', '8', '0', '1', '2', '3', '4', '5', '6', '7', '8', '0');
		var _num = "";
		for (var i = 0; i < 4; i++) {
			_num = _num + _data[Math.floor(Math.random() * _data.length)];
			_random_code = _num;
		}
		
		if(_type=='password'){
			_type='[Guppii]임시 비밀번호는 ' + _random_code + '입니다. 로그인 시 임시 비밀번호를 사용하여 주세요.';
			tempPassword(_phone,_random_code);
		}else if(_type=='auth'){
			_type='[Guppii]인증번호는 '+ _random_code + '입니다.';
			$("#authBtn").off('click').on('click', function(event) {
				event.preventDefault();
				if($('#authPhone').val()==''){
					$('#authPhone').focus();
				}else{
					check_certinum(_phone,_random_code);
				}
			});
		}

		$.ajax({
			type : "POST",
			crossDomain : true,
			url : "http://api.coolsms.co.kr/sendmsg?user=insnins&password=xii12345&to=" + userJoinInfo._phone + "&from=18779882&text="+_type,
			success : function(data) {
				

			}
		});
	};
	
	/*전화번호 인증번호 확인*/ 
	var check_certinum = function(_phone,_random_code) {
		var certinum = $("#authPhone").val();
		if (certinum == _random_code) {
			joinBlock2.check_phone=1;
			alert('인증번호가 확인되었습니다.');
			
			$('#authBtn').remove();
			$("#authPhone").val('인증번호 확인').attr('disabled' , 'disabled').css('color' , 'white').css('background' , 'rgb(253,120,14)').css('border' , '1px solid rgb(253,120,14)');
			$('#checkMail p').html("인증번호 확인 완료. 가입하기 버튼을 눌러주세요.")

		} else {
			alert('인증번호 4자리를 정확히 입력해주세요.');
			$("#authPhone").focus();

			return false;
		}
		
	}; 

	/*회원가입*/
	var joinByPhone = function() {
		userJoinInfo._name= $('#joinNick').val();
		userJoinInfo._password= $('#joinPW').val();
		userJoinInfo._birth=$('select[name="year"]').val()+'-'+$('select[name="month"]').val()+'-'+$('select[name="day"]').val();
		userJoinInfo._description=$('#selfIntro').val();

		
		if($('.genderW').attr('checked') == 'checked'){
			userJoinInfo._gender = 'female';
		}

		
		$.ajax({
			type : "post",
			url : ajaxURL + "account.php?action=joinByPhone",
			dataType : "json",
			data : {
				phone : userJoinInfo._phone,
				name : userJoinInfo._name,
				password : userJoinInfo._password,
				gender : userJoinInfo._gender,
				birthday : userJoinInfo._birth,
				description : userJoinInfo._description
			},
			success : function(result) {
				$.each(result, function() {
					sessionStorage.setItem('user_id', this.user_id);
					sessionStorage.setItem('user_name', this.name);
					sessionStorage.setItem('user_image' , this.image);

				});
				$('section').hide();$('section:nth(3)').fadeIn();
				$('.joinComplete b').html(sessionStorage.getItem('user_name'));
					
			}
		});
	};
	
	var checkInput = function(){
		
		var _name = $('#joinNick').val();
		var _password = $('#joinPW').val();

		
		if (_name == "닉네임 : 이름 또는 별명" || _name == "") {
			alert("닉네임을 입력해주세요");
			$("#joinNick").focus();
		} else if (_password == "비밀번호 : 8자리 이상 영문,숫자" || _password == "") {
			alert('비밀번호를 입력 해 주세요');
			$("#joinPW").focus();
		} else if (_password != $('#joinRePW').val()){
			alert('비밀번호가 일치하지 않습니다.');
			$("#joinRePW").focus();
		} else{
			if(window.location.href.indexOf('seller')==-1){
				joinByPhone();
			}else{
				$('section').hide();$('section:nth(3)').fadeIn();
				
			}
		}		
	};
	
	var checkPassword = function(){
		var _password = $('#joinPW').val();
		var _password2 = $('#joinRePW').val();
		
		if(_password && _password2) {
		
			/* 두 필드의 값이 서로 다를 때*/
			if(_password!=_password2){
		
				// status 필드에 일치하지 않는다는 문장 출력*/
				$('#status').html("[ 일치하지 않습니다 ]");
				$('#status').css('color','RED');
			
			/* 두 필드의 값이 동일 할 때*/
			} else {
			
				/* status 필드에 일치한다는 문장 출력*/
				$('#status').html("[ 일치합니다 ]");
				$('#status').css('color','GREEN');
			
			}
		
		/*값이 없을 때*/
		} else {
		
			/* 아무것도 입력이 안 되어 있으므로 비밀번호를 입력해 달라는 메세지를 status 필드에 출력 함*/ 
			$('#status').html("[ 비밀번호를 입력해 주세요 ]");
		}
	};
	
	/*임시 비밀번호*/
	var tempPassword = function(_phone,_newPassword) {

		$.ajax({
			type : "post",
			url : ajaxURL + "account.php?action=tempPassword",
			data : {
				phone : _phone,
				password : _newPassword
			},
			success : function(result) {
			}
		});
	};
	
	/*비밀번호 바꾸기*/
	var changePassword = function(){
		var _user_id = sessionStorage.getItem('user_id');
		var _oldPassword = $('#oldPassword').val();
		var _newPassword = $('#newPassword').val();
		var _newPassword2 = $('#newPassword2').val();
		
		if(!_oldPassword || !_newPassword || !_newPassword2){
			alert("입력값을 확인하여 주세요.");
			return;
		}
		
		if(_newPassword!=_newPassword2){
			alert(DISMATCH_NEW_PASSWORD);
			return;
		}
		
		$.ajax({
			type : "post",
			url : ajaxURL + "account.php?action=changePassword",
			data : {
				user_id : _user_id,
				newPassword : _newPassword,
				oldPassword : _oldPassword
			},
			success : function(result) {
				if(result==true){
					alert(SUCCESS_MODIFY_PASSWORD);
					$('#editPw,.modalBg').hide();
					$('#pwdTable input').val('');
				}else if(result==false){
					alert(DISMATCH_OLD_PASSWORD);
				}
	
					
			}
		});
	};
	/*회원정보 수정하기*/
	var modifyInfo = function(){
		var _description = $('.left table:nth(0) tr:nth(6) td input').val();
		var _user_id = sessionStorage.getItem('user_id');
		$.ajax({
			type : "post",
			url : ajaxURL + "account.php?action=modifyInfo",
			data : {
				user_id : _user_id,
				description : _description			
			},
			success : function(result) {
				sessionStorage.setItem('user_image', result);
				alert(SUCCESS_MODIFY_INFO);
				location.reload();
			}
		});
	};
	
	/*account template*/
	var template = {
		LoginBlock : function(selecter) {
			var info='';
			info += '<input onkeydown="javascript:if(event.keyCode==13){Account.loginByPhone();}" type="text" id="logID" class="loginBar" />';
			info += '<input onkeydown="javascript:if(event.keyCode==13){Account.loginByPhone();}" type="password" id="logPW" class="loginBar" />';
			info += '<button id="mainLoginBtn" class="loginBtn" >로그인</button>';	
			info += '<button id="fbLoginBtn" class="fbBtn">페이스북 로그인</button>';
			info += '<div class="clear"></div>';
			info += '<div class="extras">';
			info += '<input id="autoCheckbox" type="checkbox" /> <a>로그인 유지</a> | ';
			info += '<a href="join.php">회원가입</a> | ';
			info += '<a href="findpw.php">비밀번호 찾기</a>';
			info += '</div>';			
			$(selecter).append(info);

			Sns.eventListenner(); //facebook 버튼 이벤트 리스너 
		},
		LoginedBlock : function(result,selecter) {
			if(result.description == '' || !result.description){
				result.description = '한줄소개가 없습니다.';
			}
			var info = '';
			info += '<div class="thumbWrap">';
			info += '<img src="'+result.image+'" alt="thumb_profile_big"  />';
			info += '</div>';
			info += '<div class="infoWrap">';
			info += '<a href="mypage.php">'+result.name+'</a>';
			info += '<ul><li class="gp">GP <b>'+result.point+'</b></li><li>리뷰 <b>'+result.talkCount+'</b>개</li>';
			info += '<li>유용해요 <b>'+result.usefulCount+'</b>번</li></ul>';
			info += '</div><div class="clear"></div>';
			info += '<div class="infoLink"> <ul>';
			info += '<li class="first-child"><a href="mycoupon.php">쿠폰 <b>'+result.couponCount+'</b>장</a></li>';
			info += '<li><a href="mystore.php">단골 <b>'+result.favoriteCount+'</b>개</a></li>';
			info += '<li><a href="myfriends.php">친구 <b>'+result.friendCount+'</b>명</a></li>';
			//info += '<li><a href="myfriend.php">친구요청 <b>'+result.friendRequestCount+'</b>명</a></li>';
			info += '<div class="clear"></div></ul></div>';
			info += '<div class="introWrap"><a><b><span>'+result.name+'</span>의 한 줄 소개</b>'+result.description+'</a></div>';
			
			$(selecter).append(info);	
		}
	};
 
		
	
})(window);
